﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace FlexiCommerce.Persistence
{
    public class FlexiTypeDescriptionProvider : System.ComponentModel.TypeDescriptionProvider
    {


        public FlexiTypeDescriptionProvider(Type type)
            : this(type, TypeDescriptor.GetProvider(type))
        {
            this.Type = type;
        }

        public FlexiTypeDescriptionProvider(Type type, TypeDescriptionProvider parentProvider)
            : base(parentProvider)
        {
            this.Type = type;
        }

        private Type Type { get; set; }

        public override System.ComponentModel.ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
        {
            FlexiTypeDescriptor ad =
             new FlexiTypeDescriptor(base.GetTypeDescriptor(objectType, instance), this.Type);
            return ad;
        }
      
    }
    public class FlexiTypeDescriptor : System.ComponentModel.CustomTypeDescriptor
    {
        #region Constructors

        public FlexiTypeDescriptor(ICustomTypeDescriptor parent, Type type)
            : base(parent)
        {
            this.Type = type;
        }

        #endregion Constructors

        #region Properties

        private Type Type
        {
            get; set;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Returns the collection of attributes for a given table
        /// </summary>
        /// <returns>AttributeCollection</returns>
        public override AttributeCollection GetAttributes()
        {
            AttributeCollection attr = base.GetAttributes();
            return attr;
        }

        public override PropertyDescriptorCollection GetProperties()
        {
            List<PropertyDescriptor> propertyDescriptors = new List<PropertyDescriptor>();

            foreach (PropertyDescriptor propDescriptor in base.GetProperties())
            {


                propertyDescriptors.Add(propDescriptor);
         

            }
            return new PropertyDescriptorCollection(propertyDescriptors.ToArray(), true);
        }

        #endregion Methods

        #region Nested Types

    

        #endregion Nested Types
    }

    public static class HelperExtansionMethods
    {
        #region Methods

        public static Boolean HasAttribute<T>(this PropertyDescriptor descriptor)
            where T : Attribute
        {
            Boolean value = false;
            for (int i = 0; i < descriptor.Attributes.Count && !value; i++)
            {
                value = (descriptor.Attributes[i] is T);
            }

            return value;
        }

        #endregion Methods
    }

}
